package com.adopt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
public class VarifyCodeController {
    @RequestMapping("/getVarifyCode")
    public void getVarifyCode(HttpSession session, HttpServletResponse response) throws Exception {
        //图片对象
        BufferedImage bi = new BufferedImage(35,15,BufferedImage.TYPE_INT_RGB);
        //画笔
        Graphics2D g=(Graphics2D) bi.getGraphics();
        //设置画笔颜色
        g.setColor(Color.white);
        //填充背景
        g.fillRect(0,0,80,35);
        //设置画笔为蓝色
        g.setColor(Color.blue);
        //产生验证码,4位
        String str="23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
        StringBuilder s = new StringBuilder();
        for (int i = 0;i < 4;i++){
            //产生随机下标
            int index = new Random().nextInt(str.length());//nextInt范围[0,1)--->nextInt范围0,str.length-1
            String randomChar  = str.charAt(index)+"";
            s.append(randomChar);
        }
        g.drawString(s.toString(),3,13);
        session.setAttribute("varifyCode",s.toString());
        System.out.println("验证码:"+s.toString());
        ImageIO.write(bi,"JPEG",response.getOutputStream());
    }
}